package me.alide.modules.survey.controller;

import lombok.extern.slf4j.Slf4j;
import me.alide.common.exception.RRException;
import me.alide.common.utils.R;
import me.alide.modules.survey.entity.DictEntity;
import me.alide.modules.survey.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Anzhen
 * @description:
 * @PROJECT_NAME: alide
 * @create: 2021-07-25 14:30
 **/
@Slf4j
@RestController
@RequestMapping("/busDict")
public class DictController {

    @Autowired
    private DictService dictService;

    /**
     * 增
     * @param dictEntity
     * @return
     */
    @RequestMapping("save")
    public R save(@RequestBody DictEntity dictEntity) {
        try {
            int save = dictService.save(dictEntity);
            if (save == 1) {
                log.info("保存成功");
            } else {
                throw new RRException("保存失败", 500);
            }
        } catch (Exception e) {
            log.error("保存失败", e);
            return R.error(500, e.getMessage());
        }
        return R.ok();
    }

    /**
     * 删
     * @param ids
     * @return
     */
    @RequestMapping("delete")
    public R delete(@RequestBody Long[] ids) {
        try {
            int deleteCount = dictService.delete(ids);
            if (deleteCount == 1) {
                log.info("删除成功{}条", deleteCount);
            } else {
                throw new RRException("删除失败", 500);
            }
        } catch (Exception e) {
            log.error("删除失败", e);
            return R.error(500, e.getMessage());
        }
        return R.ok();
    }

    /**
     * 改
     */
    @RequestMapping("update")
    public R update(@RequestBody DictEntity dictEntity) {
        try {
            int save = dictService.update(dictEntity);
            if (save == 1) {
                log.info("更新成功");
            } else {
                throw new RRException("更新失败", 500);
            }
        } catch (Exception e) {
            log.error("更新成功", e);
            return R.error(500, e.getMessage());
        }
        return R.ok();
    }

    /**
     * 查
     */
    @RequestMapping("queryAll")
    public List<DictEntity> queryAll() {
        try {
            List<DictEntity> list = dictService.queryAll();
            return list;
        } catch (Exception e) {
            log.error("查询失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 查
     */
    @RequestMapping("queryById")
    public DictEntity queryById(@RequestParam Long id) {
        try {
            return dictService.queryById(id);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }


}
